from src.model import Message
from base import BaseHandler
from src.utilities.prefetcher import prefetch_refprop
from src.utilities.cache import memoize
import time

class InitHandler(BaseHandler):
	MESSAGES_COUNT = 20
	OPTIMIZATION_GAP = 2 # increase to better performance

	@staticmethod
	@memoize('init_update_%d')
	def cached_content(timestamp, self):
		return self.content()

	def content(self):
		messages = Message.all().filter('is_blocked', False).order('-changed').fetch(InitHandler.MESSAGES_COUNT, 0)
		prefetch_refprop(messages, Message.person)

		return self.generate_template('messages.json', {
				'messages':messages
		})    

	def get(self):
		timestamp = int(time.time())
		timestamp = timestamp - (timestamp % InitHandler.OPTIMIZATION_GAP)
		content = InitHandler.cached_content(timestamp, self)
		self.write_response(content, content_type='application/json')
